﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using Meow.Core.Log;
using Silk.NET.OpenGL;

namespace Meow.Core.Render
{
    /// <summary>
    /// 基础的Renderer, 使用GL
    /// </summary>
    public class Renderer: IDisposable
    {
        private static GL _gl; // 这是个对GL上下文的引用，Silk这里提供了这个概念引用确实挺特别的

        private uint _vao;

        ShaderProgram shaderProgram;
        VertexBuffer<Vector3> vertexBuffer;
        Color _clearColor;
        public Renderer(GL gL, Color clearColor)
        {
            _gl = gL;
            _clearColor = clearColor;
            _gl.ClearColor(_clearColor);

            _vao = _gl.GenVertexArray();
            _gl.BindVertexArray(_vao);

            OnLoad();
        }

        private unsafe void OnLoad()
        {

            shaderProgram = new ShaderProgram(_gl);
            shaderProgram.GenVertexAndFragmentShaderAndLink(TestShader.vertexCode, TestShader.fragmentCode);

            shaderProgram.AddVertexAttribPointer(0, VertexAttribPointerType.Float, 3, 3 * sizeof(float), 0, false);


            Vector3[] vertices =
        {
            new Vector3( 0.5f,  0.5f, 0.0f),
            new Vector3( 0.5f, -0.5f, 0.0f),
            new Vector3(-0.5f, -0.5f, 0.0f),
            new Vector3(-0.5f,  0.5f, 0.0f)
        };

            uint[] indices =
        {
            0u, 1u, 3u,
            1u, 2u, 3u
        };

            vertexBuffer = new VertexBuffer<Vector3>(_gl);
            vertexBuffer.SetVertexData(vertices, vertices.Length, indices, indices.Length);

        }

        public void Clear()
        {
            _gl.Clear(ClearBufferMask.ColorBufferBit);
        }

        static int cp;

        public unsafe void OnRender(int fps)
        {
            Clear();

            _gl.BindVertexArray(_vao);

            vertexBuffer.Bind();

            shaderProgram.Activate();

            cp = ++cp % fps;
            var cc = (float)cp / fps;
            shaderProgram.SetUniform4("colorD", new System.Numerics.Vector4(cc, 1 - cc, cc * 0.5f, 1));

            _gl.DrawElements(PrimitiveType.Triangles, 6, DrawElementsType.UnsignedInt, (void*)0);
            DebugUtil.CheckGLError(_gl);
        }

        public void Dispose()
        {
            _gl.DeleteVertexArray(_vao);
        }
    }
}
